import classNames from 'classnames';
import { useContext, useEffect, useMemo, useState } from 'react';
import { useMediaPredicate } from 'react-media-hook';
import { useDispatch, useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import BackButton from 'src/component/BackButton';
import Button from 'src/component/Button';
import Pagination from 'src/component/Pagination';
import RoundDateFilter from 'src/component/RoundDateFilter';
import RoundSelect from 'src/component/RoundSelect';
import SelectOption from 'src/component/SelectOption';
import { Ui } from 'src/constant/Env';
import { MediaQuery } from 'src/constant/Media';
import { Page } from 'src/constant/Page';
import { ThemeContext } from 'src/context/ThemeContext';
import { useDateFilter } from 'src/hook/useDateFilter';
import { usePagination } from 'src/hook/usePagination';
import IcUsdt from 'src/image/ic-usdt.svg';
// import { Balance } from 'src/model/Balance';
// import { BalanceTransaction } from 'src/model/Property';
import { RootState } from 'src/redux/store';
import { openSnackbar } from 'src/redux/uiSlice';
// import { getBalance, getBalanceTransactions, getFillById } from 'src/service/propertyService';
import { getMyDetails } from 'src/service/orderService'
import { getUserInfo } from 'src/service/userService'
import { bnFormat } from 'src/util/bigNumber';
import Card from './component/Card';
import RedirectModal from './component/RedirectModal';
import Table from './component/Table';
import style from './Property.module.scss';


type Balance = any
type BalanceTransaction = any



const Property = () => {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const { IcEmpty } = useContext(ThemeContext).image;
  // const { accountInfo } = useSelector((rootState: RootState) => rootState.auth);
  const { offset, limit, setCount, paginationProps } = usePagination();
  const { begin, end, dateFilterProps } = useDateFilter();
  const [open, setOpen] = useState<boolean>(false);
  const [balance, setBalance] = useState<Balance>();
  const [total, setTotal] = useState<number>(0);
  const [count2, setCount2] = useState<number>(0);
  const [accountInfo, setAcountInfo] = useState<Balance>()
  const [filterType, setFilterType] = useState<string>('全部');
  const [shuaxin, setShuaxin] = useState<boolean>(false)
  const [transactionArray, setTransactionArray] = useState<Array<BalanceTransaction>>([]);
  const [allDatas, setAllDatas] = useState<Array<BalanceTransaction>[]>([]);
  const isBiggerThanMd = useMediaPredicate(MediaQuery.Md);
  const token = localStorage.getItem("token")
  const uMail = localStorage.getItem("uMail")
  const options = useMemo(() => {
    if (Ui === 'seller')
      return [
        'all',
        'ask',
        'deposit',
        'withdrawal',
        'manipulation',
        'agent-rebate',
        'parent-rebate',
      ];
    if (Ui === 'buyer') return ['all', 'bid', 'deposit', 'withdrawal', 'manipulation'];

    return [];
  }, []);


  useEffect(() => {
    if (!shuaxin) return
    // console.log('开启定时器')
    const timer = setInterval(() => {
      // console.log('进入定时器')
      // 注:在setCount中使用箭头函数是最好方式之一,只有一个timer生成
      const userData = {
        token: token,
        uMail: uMail
      }
      getUserInfo(userData).then(res => {
        if (res.success) {
          setAcountInfo(res.list[0])
        }
      })
    }, 10000)
    return () => {
      // console.log('清除定时器')
      clearInterval(timer)
    }
  }, [shuaxin]) //如果设置count依赖,会有多个timer生成,销毁


  useEffect(() => {
    const userData = {
      token: token,
      uMail: uMail
    }
    getUserInfo(userData).then(res => {
      if (res.success) {
        setAcountInfo(res.list[0])
        setShuaxin(true)
      }
    })
  }, [])

  useEffect(() => {
    const fcoin = accountInfo?.FCoin || 0;
    const fdcoin = accountInfo?.FdCoin || 0;
    let num = fdcoin + fcoin
    setTotal(num)

  }, [accountInfo?.FCoin, accountInfo?.FdCoin]);

  useEffect(() => {
    if (!accountInfo?.FID) return
    getMyDetails({
      FUserID: accountInfo?.FID,
      FState: filterType,
      Sdate: begin,
      Edate: end,
      token: token,
    }).then(res => {
      if (res.success) {
        setAllDatas(res.list);
        setCount(res.list.length);
      }
    })
  }, [begin, end, limit, filterType, accountInfo?.FID]);


  useEffect(() => {
    if (allDatas?.length < 0) return
    let len = offset + limit
    let data = allDatas.slice(offset, len)
    setTransactionArray(data);
  }, [offset, limit, allDatas])


  const navigateCallback = (transaction: BalanceTransaction) => {

    switch (transaction.FNote) {
      case '售出': {
        navigate(`${Page.Order}/${transaction.referenceId}`);
        break;
      }

    }
  };

  const onWithdrawalClick = () => {
    if (accountInfo?.FGoogle == "启用") navigate(`${Page.Withdrawal}`);
    else setOpen(true);
  };

  const onTypeFilterChange = (value: string) => {
    paginationProps.setPage(1);
    setFilterType(value);
  };


  return (
    <div>
      <div className={style.backButton}>
        <BackButton />
      </div>
      <div className={style.heading}>{"USDT 交易明细"}</div>
      <div className={style.amountBlock}>
        <div className={style.propertyHeadingBlock}>
          <div className={style.propertyHeading}>
            <img src={IcUsdt} />
            USDT
          </div>
          <div className={style.amount}>
            <div className={style.label}>总共</div>
            <div className={style.value}>{bnFormat((total) ?? null)}</div>
          </div>
        </div>
        {/* <div className={classNames(style.amountItem, style.item)}>
          <div className={style.label}>总共</div>
          <div className={style.value}>{bnFormat(balance?.total ?? null)}</div>
        </div> */}
        <div className={style.item}>
          <div className={style.label}>可用余额</div>
          <div className={style.value}>{bnFormat(accountInfo?.FCoin ?? null)}</div>
        </div>
        <div className={style.item}>
          <div className={style.label}>冻结</div>
          <div className={style.value}>{bnFormat(accountInfo?.FdCoin ?? null)}</div>
        </div>
        <div className={style.buttons}>
          <Button size="small" onClick={() => navigate(`${Page.Deposit}`)}>
            充值
          </Button>
          <Button size="small" onClick={onWithdrawalClick}>
            提领
          </Button>
        </div>
      </div>
      <div className={style.transactionBlock}>
        <div className={style.filter}>
          <RoundDateFilter onChange={() => paginationProps.setPage(1)} {...dateFilterProps} />
          <div className={style.type}>
            <RoundSelect
              label={"类型"}
              defaultValue="全部"
              onChange={onTypeFilterChange}
            >
              <SelectOption value="全部">
                全部
              </SelectOption>
              <SelectOption value="售出">
                售出
              </SelectOption>
              <SelectOption value="充值">
                充值
              </SelectOption>
              <SelectOption value="提领">
                提领
              </SelectOption>
              <SelectOption value="修正">
                修正
              </SelectOption>
              <SelectOption value="团队返佣收入">
                团队返佣收入
              </SelectOption>
              <SelectOption value="阶级返佣收入">
                阶级返佣收入
              </SelectOption>
            </RoundSelect>
          </div>
        </div>
        <div className={style.divider} />
        {transactionArray?.length === 0 && (
          <div className={style.emptyImg}>
            <img src={IcEmpty} />
          </div>
        )}
        {transactionArray &&
          transactionArray?.length > 0 &&
          (isBiggerThanMd ? (
            <Table data={transactionArray} navigateCallback={navigateCallback} />
          ) : (
            <Card data={transactionArray} navigateCallback={navigateCallback} />
          ))}
      </div>
      <div className={style.pagination}>
        <Pagination {...paginationProps} />
      </div>
      <RedirectModal open={open} onClose={() => setOpen(false)} />
    </div>
  );
};

export default Property;
